//      common.h
//      
//      Copyright 2012 Piotr <piotr@piotr-dell>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED

#include <stdio.h>
#include <sys/types.h>
#include <time.h>

// indeks deskryptora potoku
#define PIPE_RECV   		0
#define PIPE_SEND   		1

// Liczba procesów i zasobów
#define RESOURCE_COUNT		10
#define PROCESS_COUNT       5

enum lockType { DLM_LOCK_CR,
				DLM_LOCK_CW,
				DLM_LOCK_PR,
				DLM_LOCK_PW,
                DLM_LOCK_EX,
                DLM_LOCK_COUNT };

enum reqType { DLM_REQ_LOCK,
			   DLM_REQ_UNLOCK,
			   DLM_REQ_TRYLOCK,
			   DLM_INIT,
			   DLM_DESTROY,
			   DLM_TERMINATE_PROCESS,
               DLM_FORK,
               DLM_COUNT };
			   
enum errorCode { DLM_ERR_OK,
                 DLM_ERR_ALREADY_LOCKED,
				 DLM_ERR_CANNOT_LOCK,
				 DLM_ERR_NO_SUCH_RESOURCE,
				 DLM_ERR_NO_SUCH_LOCK,
				 DLM_ERR_TIMEOUT,
                 DLM_ERR_UKNOWN,
                 DLM_ERR_COUNT };

struct message {
    //int messageType;	nigdzie nie było używane
    pid_t senderPid;
    int requestType;
    int resource_id;
    int lock_type;
    long timeout;
    int returnValue;
};

//opis procesu potomnego
struct child_data {
    int recv_pipe[2];           //deskryptory potoku do odbierania wiadomości od procesu potomnego
    int send_pipe[2];           //deskryptory potoku do wysyłania wiadomości do procesu potomnego
    pid_t pid;                  //PID procesu potomnego
};

//blokada na zasobie
struct lock {
    int resource_id;
    int lock_type;              //typ blokady
    struct child_data owner;   //zakładający blokadę
};

//opis oczekujacego na zasob
struct lock_waiter {
    struct lock resource_lock;
    suseconds_t timestamp;      //czas założenia blokady
    long timeout;               //milisekundy do upłynięcia
};

struct timer_descriptor
{
	timer_t timerid;
	lock_waiter waiter;
	message waiterReply;
};


int commonTest();
long current_time_miliseconds();

#endif
